package org.hades.corelib.utils.device

import android.Manifest
import android.app.Application
import android.os.Environment
import org.hades.corelib.utils.AppUtils.app
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


/**
 * 1. file  路径提供者
 * 2. file  文件存取
 * 3. APP   空间检查
 */
object FileUtils {
    var MIN_SPACE = 100

    /**
     * 外置存储，读写权限
     */
    private val permissions = arrayOf<String>(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    /**
     * get Android Cache File
     *
     * @return context.getCacheDir()
     */
    fun provideCacheFile(): File? {
        val app: Application? = app
        return app?.cacheDir
    }

    fun provideDiskFile(): File {
        val file: File? = provideCacheFile()
        val disk = File(file, "disk")
        if (!disk.exists()) disk.mkdirs()
        return disk
    }

    fun provideImageFile(): File {
        val file: File? = provideCacheFile()
        val disk = File(file, "images")
        if (!disk.exists()) disk.mkdirs()
        return disk
    }

    @Throws(IOException::class)
    fun provideImageStampFile(): File? {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
        val imageFileName = "JPEG_" + timeStamp + "_"
        val file: File = provideCacheFile() ?: return null
        val IMAGE_DIR = "images"
        return provideImageCacheFile(file, IMAGE_DIR, imageFileName)
    }

    @Throws(IOException::class)
    fun provideImageCacheFile(dir: File?, child: String?, name: String?): File? {
        val image: File
        val imageFile = File(dir, child)
        if (!imageFile.exists()) {
            val mkdirs: Boolean = imageFile.mkdirs()
            if (!mkdirs) return null
        }
        image = File.createTempFile(
            name,  /* prefix */
            ".jpg",  /* suffix */
            imageFile /* directory */
        )
        return image
    }

    /**
     * check file how has low space
     *
     * @param file the file need to write
     * @return has space true else false
     */
    fun isEnoughSpace(file: File): Boolean {
        return isEnoughSpace(file, MIN_SPACE.toLong())
    }

    /**
     * check file how has low space
     *
     * @param file the file need to write
     * @param size need how match space MB
     * @return has space true else false
     */
    fun isEnoughSpace(file: File, size: Long): Boolean {
        val space: Long = file.usableSpace shr 20
        return space >= size
    }
}